<template>
  <div>
    <div>
      <el-cascader
        v-model="parentId"
        :options="navTree"
        :props="{ checkStrictly: true, label: 'name', value: '_id' }"
        clearable
        size="mini"
      ></el-cascader>
      <el-button type="primary" @click="addShow" size="mini">新增</el-button>
    </div>

    <el-table
      :data="tableData"
      border
      v-loading="isLoading"
      style="width: 100%; margin-top: 20px"
      row-key="id"
      size="mini"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        v-for="(item, index) in tables"
        :prop="item.prop"
        :label="item.label"
        width="150"
      >
      </el-table-column>
      <el-table-column fixed="right" label="菜单类型" align="center">
        <template slot-scope="scope">
          <el-tag
            size="mini"
            :type="scope.row.menuType == 1 ? 'primary' : 'success'"
          >
            {{ scope.row.menuType == 1 ? '菜单' : '按钮' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="update(scope.row)"
            >编辑</el-button
          >
          <el-button type="text" size="small" @click="del(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="'新增菜单'" :visible.sync="showDialog">
      <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="路由" prop="url">
          <el-input v-model="formData.url"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="formData.icon"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="formData.orderNum"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="menuType">
          <el-radio v-model="formData.menuType" label="1">菜单</el-radio>
          <el-radio v-model="formData.menuType" label="2">按钮</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="confirm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { addMenuList, delMenuList } from '@/api/menu'
import { mapState, mapActions } from 'vuex'
import { addRouter } from '@/permission'
import { MessageBox } from 'element-ui'
import router from '@/router/index'
export default {
  computed: {
    ...mapState('navMenu', ['navTree']),
  },
  data() {
    return {
      tableData: [],
      options: [
        {
          value: 'zhinan',
          label: '指南',
          children: [
            {
              value: 'shejiyuanze',
              label: '设计原则',
              children: [
                {
                  value: 'yizhi',
                  label: '一致',
                },
                {
                  value: 'fankui',
                  label: '反馈',
                },
                {
                  value: 'xiaolv',
                  label: '效率',
                },
                {
                  value: 'kekong',
                  label: '可控',
                },
              ],
            },
          ],
        },
      ],
      formData: {
        name: '',
        url: '',
        icon: '',
        orderNum: '',
        menuType: '1',
      },
      rules: {
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
        ],
        url: [{ required: true, message: '请输入路由', trigger: 'blur' }],
      },
      showDialog: false,
      tables: [
        {
          label: 'id',
          prop: 'id',
          //type设置空值可以使树形表格箭头移到后一项
          type: '',
          width: 50,
        },
        {
          label: '名称',
          prop: 'name',
        },
        {
          label: '图标',
          prop: 'icon',
        },
        {
          label: '路由',
          prop: 'url',
        },
        {
          label: '排序',
          prop: 'orderNum',
        },
      ],
      parentId: null,
      action: 0, // 0新增   1修改
      isLoading: false,
    }
  },
  methods: {
    ...mapActions('navMenu', ['getMenuList']),
    async queryList() {
      this.isLoading = true
      this.tableData = await this.getMenuList().finally(
        () => (this.isLoading = false)
      )
    },
    addShow() {
      this.showDialog = true
      this.action = 0
    },
    cancel() {
      this.showDialog = false
      this.$refs.form.resetFields()
    },
    confirm() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          const { errorCode } = await addMenuList({
            action: this.action,
            parentId: this.parentId
              ? this.parentId[this.parentId.length - 1]
              : null,
            ...this.formData,
          })
          if (errorCode === '0000') {
            this.$message({
              showClose: true,
              message: '新增成功',
              type: 'success',
            })
            this.cancel()

            // 重新加载菜单
            this.tableData = await this.getMenuList()

            let routers = addRouter(this.tableData)
            for (let children of routers) {
              router.addRoute('首页', children)
            }
          }
        }
      })
    },
    update(row) {
      const { name, url, icon, orderNum, _id, parentId } = row
      const menuType = row.menuType.toString()

      this.$nextTick(() => {
        this.formData = { name, url, icon, orderNum, menuType, _id, parentId }
        this.action = 1
      })
      this.showDialog = true
    },
    async del(row) {
      await MessageBox.confirm('此操作将删除菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      const { errorCode } = await delMenuList({ _id: row._id })
      if (errorCode === '0000') {
        this.$message({
          type: 'success',
          message: '删除成功',
        })
        this.parentId = null
        //查询菜单
        this.tableData = await this.getMenuList()
      }
    },
  },
  created() {
    this.queryList()
  },
}
</script>
